package com.eyas.im.client.nio.handler;

import com.eyas.im.protocol.decoder.Decoder;
import com.eyas.im.protocol.encoder.Encoder;
import com.eyas.im.protocol.protocol.StringProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

public class ConsoleSocketClientHandler extends AbstractSocketClientHandler<StringProtocol> {
    private final static Logger logger = LoggerFactory.getLogger(ConsoleSocketClientHandler.class);
    private final CountDownLatch countDownLatch = new CountDownLatch(1);
    public ConsoleSocketClientHandler(Encoder<StringProtocol> encoder, Decoder<StringProtocol> decoder, int bufferCapacity) {
        super(encoder, decoder, bufferCapacity);
    }

    public void sync() {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterConnected() {
        logger.debug("client连接到server上");
        countDownLatch.countDown();
    }

    @Override
    public void onDataDecode(StringProtocol decodeData) {
        if(decodeData!=null&&decodeData.getMessage()!=null) {
            StringBuilder stringBuilder = new StringBuilder("服务端说:>>>");
            decodeData.getMessage().forEach(msg->{
                stringBuilder.append("[").append(msg).append("],");
            });

            System.out.println(stringBuilder.toString());
        }
    }

    @Override
    public void beforeClose() {
        logger.debug("client与server间的连接断开");
    }
}
